<?php 
use Think\Model;
/**
 * 接口查询条件string转array
 * __表示两个条件参数的连接符
 * |= 表示参数的值
 * #= 表示参数值的关联关系
 */
function condition_to_array($condition_str){
	$tmparr = array();
	$tmp = explode('__',$condition_str);
	foreach($tmp as $t){
		$tt = explode('|_|',$t);
		if(count($tt)!= 2){
			return false;
		}else{
			$ttt = explode('*_*',$tt[1]);
			if(count($ttt) == 2){
				$tttt = array($ttt[0],$ttt[1]);
			}else{
				$tttt = $tt[1];
			}
			$tmparr[$tt[0]] = $tttt;
		}
	}
	return $tmparr;
}

/**
 * 将查询条件数组编译成字符串
 */
function condition_to_str($condition_array){
	$tmparr = array();
	foreach($condition_array as $key=>$val){
		$tmp = $val;
		if(is_array($val)){
			$tmp = implode('*_*',$val);
		}
		$tmparr[] = $key.'|_|'.$tmp;
	}
	return implode('__',$tmparr);
}

/**
 * 本地的，利用了session，生成一个token
 * @param unknown $key
 * @return string
 */
function token_create($key){
	$tokenObj = new Token();
	return $tokenObj->grante_token($key);
}

/**
 * 本地的，利用了session，检测是否为token
 * @param unknown $key
 * @param unknown $token
 * @return Ambigous <string, boolean>
 */
function token_check($key,$token){
	$tokenObj = new Token();
	return $tokenObj->is_token($key, $token);
}

/**
 * 本地的，利用了session删除一个token
 * @param unknown $key
 */
function token_del($key){
	$tokenObj = new Token();
	$tokenObj->drop_token($key);
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function format_bytes($size, $delimiter = '') {
	$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
	for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
	return round($size, 2) . $delimiter . $units[$i];
}
/*
function array_column($array,$column_name){
	return array_map(function($element) use($column_name){return $element[$column_name];}, $array);
}
*/
/*
 * send 短信
* return -1:No user ,-3:短信数量不足  , -4:手机格式不正确 , 1:短信已经发送
*/
function SMS_SEND($mobile,$msg){
	$msg = mb_convert_encoding($msg, "GBK", "UTF-8");
	$url="http://sms.webchinese.cn/web_api/?Uid=amanwu&Key=2605afe65369a30b7f30&smsMob=$mobile&smsText=$msg";
	return SMSAPI($url);
}
//短信接口调用
function SMSAPI($url){
	if(function_exists('file_get_contents'))
	{
		$file_contents = file_get_contents($url);
	}
	else
	{
		$ch = curl_init();
		$timeout = 5;
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$file_contents = curl_exec($ch);
		curl_close($ch);
	}
	return $file_contents;
}

/**
 * 中文转拼音
 * @param unknown $str
 */
function _pingyin($str){
	$zh = new \Common\ORG\CUtf8_PY();
	return $zh->trimall($zh->encode($str,'all')); //编码为全拼音
}

/**
 * 输出json，作为api接口的统一返回
 */
function _apiReturn($status,$info,$data,$url){
	// 返回JSON数据格式到客户端 包含状态信息
	header('Content-Type:application/json; charset=utf-8');
	header("Access-Control-Allow-Origin: *");  //跨域请求
	exit(json_encode(ajax_data_tpl($status,$info,$data,$url),0));
}

//将json无法识别的字符进行转义
function _dotran($str) {
	$str = str_replace('"','//&quot;"',$str);
	$str = str_replace("/r/n",'//r//n',$str);
	$str = str_replace("/t",'//t',$str);
	$str = str_replace("//",'//',$str);
	$str = str_replace("/b",'//b',$str);
	return $str;
}

/**
 * 邮件发送函数
 */
function sendMail($to, $title, $content) {
	 
	Vendor('PHPMailer.PHPMailerAutoload');
	$mail = new PHPMailer(); //实例化
	$mail->IsSMTP(); // 启用SMTP
	$mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
	$mail->SMTPAuth = C('MAIL_SMTPAUTH'); //启用smtp认证
	$mail->Username = C('MAIL_USERNAME'); //你的邮箱名
	$mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
	$mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
	$mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
	$mail->AddAddress($to,"尊敬的客户");
	$mail->WordWrap = 50; //设置每行字符长度
	$mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
	$mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
	$mail->Subject =$title; //邮件主题
	$mail->Body = $content; //邮件内容
	$mail->AltBody = ""; //邮件正文不支持HTML的备用显示
	return($mail->Send());
}

function object_array($array){
	if(is_object($array)){
		$array = (array)$array;
	}
	if(is_array($array)){
		foreach($array as $key=>$value){
			$array[$key] = object_array($value);
		}
	}
	return $array;
}
/**
 * 执行自身api
 * @param url $api
 * return array格式的返回数据
 */
function do_self_api($api){
	$home = C('HOME_URL');
	return json_decode(file_get_contents($home.$api),true);
}

/**
 * post方式执行自身api
 * @param unknown $api
 * @param unknown $params
 */
 
function do_self_api_post($api,$params){
	$home = C('HOME_URL');
	$url = $home.$api;
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	$output = curl_exec($ch);
	curl_close($ch);
	return json_decode($output,true); //返回json数据
}


/**
 * 固定ajax数据返回格式，沿用thinkphp3.1版本的格式
 * @param unknown $status
 * @param unknown $info
 * @param unknown $data
 */
function ajax_data_tpl($status,$info,$data,$url){
	$result = array(
		'status' => $status,
		'info' => $info,
		'data' => $data,
		'url' => $url
	);
	return $result;
}
/**
 * 检测客户端传递过来的token
 * @param string $token
 */
function _check_token($token){
	return in_array($token, _create_token());
}

/**
 * 生成token
 */
function _create_token(){
	$config = C('API_TOEKN');
	$day1 = date("Y-m-d",time()); //今天 ，标准token
	$day2 = date("Y-m-d",strtotime("-1 day"));//昨天 ，用于token时间戳容错
	$day3 = date("Y-m-d",strtotime("+1 day"));//明天，用于token时间戳容错
	$tokens[] = md5($config['name'].$day1.$config['key']);
	$tokens[] = md5($config['name'].$day2.$config['key']);
	$tokens[] = md5($config['name'].$day3.$config['key']);
	return $tokens;
}
/*
 * 当参数值为空的时候，返回默认值 
 * @param 参数 $data
 * @param 默认值 $default
 */
function _param_default($param,$default){
	if(!$param) $param = $default;
	return $param;
}

/*
 * 获取某分组下面的权限树
 * @param unknown $group
 * @return Ambigous <string, multitype:Ambigous <multitype:, boolean, multitype:multitype: > >
 */
function get_auth_tree($group){

	$m = M('AuthRule');
	$map['group'] = $group;
	$map['status'] = 1;

	$data = $m->cache(true, 60)->where($map)->order('listorder desc')->select();
	$tree = new \Think\Tree();

	$tree->init($data);
	$treedata = $tree->get_tree_array(0, $str);

	return $treedata;
}

/*
 * 获取某角色分组下面的权限树
* @param unknown $group
* @return Ambigous <string, multitype:Ambigous <multitype:, boolean, multitype:multitype: > >
*/
function get_auth_tree_by_role($group,$role){
	$m = M('AuthRule');
	$map['group'] = $group;

	if($role['title'] !== 'ROLE_SUPER_ADMIN'){
		$map['id'] = array('in',$role['rules']);
	}
	
	$data = $m->cache(true, 60)->where($map)->order('listorder desc')->select();
	$tree = new \Think\Tree();

	$tree->init($data);
	$treedata = $tree->get_tree_array(0, $str);

	return $treedata;
}

/*
 * 获取分页列表数据
 */
function _uiclist($model,$map,$cur,$size,$order,$isrelation){
	if(!$size) $size = C('PAGE_SIZE');

	if(!$order){
		$pk = $model->getPk();
		$order = "$pk desc";
	}
	$isrelation ? $isrelation = true : $isrelation = false;
	if($isrelation){
		$data['list'] = $model->where($map)->order($order)->page($cur.','.$size)->relation($isrelation)->select();
	}else{
		$data['list'] = $model->where($map)->order($order)->page($cur.','.$size)->select();
	}
	$data['count'] = $model->where($map)->count();
	return $data;

}

/*
 * 前端获取分页链接
 * @param unknown $total  记录总数
 * @param unknown $size   步长
 * @param unknown $cur    当前页面No
 * @param unknown $url    基础URL
 * @param unknown $theme  分页主题
 */
function _to_page($total ,$cur = 1, $size,$url,$theme = NULL,$config = array()){
	if(!$size) $size = C("PAGE_SIZE");
	if(!$config){
		$config  = array(
				'header' => '<span class="rows">共 %TOTAL_ROW% 条记录</span>',
				'prev'   => '<<',
				'next'   => '>>',
				'first'  => '1...',
				'last'   => '...%TOTAL_PAGE%',
				'theme'  => '%first%  %upPage%  %linkPage%  %downPage%  %end% <span class="mini-page-select"></span><span>共<span class="mini-page-total-row">%totalRow%</span>条  %header% <span class="mini-page-cur">%nowPage%</span>/<span class="mini-page-total">%totalPage%</span> 页  </span>',
				'html_suffix' => '.html',
		);
	}

	if(!$theme){
		$theme = $config['theme'];
	}

	$nowPage = $cur;
	$totalRows = $total;
	$rollPage = 5;
	$lastSuffix = true; // 最后一页是否显示总页数
	/* 计算分页信息 */
	$totalPages = ceil($total/$size);  //总页数
	if(!empty($totalPages) && $nowPage > $totalPages) {
		$nowPage = $totalPages;
	}
	/* 计算分页零时变量 */
	$now_cool_page      = $rollPage/2;
	$now_cool_page_ceil = ceil($now_cool_page);
	$lastSuffix && $config['last'] = $totalPages;
	//上一页
	$up_row  = $nowPage - 1;
	$up_page = $up_row > 0 ? '<a class="prev" href="' . $url.$up_row.$config['html_suffix'] . '">' . $config['prev'] . '</a>' : '';

	//下一页
	$down_row  = $nowPage + 1;
	$down_page = ($down_row <= $totalPages) ? '<a class="next" href="' . $url.$down_row.$config['html_suffix'] . '">' . $config['next'] . '</a>' : '';

	//第一页
	$the_first = '';
	if($totalPages > $rollPage && ($nowPage - $now_cool_page) >= 1){
		$the_first = '<a class="first" href="' .$url.'1'.$config['html_suffix'] . '">' . $config['first'] . '</a>';
	}

	//最后一页
	$the_end = '';
	if($totalPages > $rollPage && ($nowPage + $now_cool_page) < $totalPages){
		$the_end = '<a class="end" href="' . $url.$totalPages.$config['html_suffix'] . '">' . $config['last'] . '</a>';
	}

	//数字连接
	$link_page = "";
	for($i = 1; $i <= $rollPage; $i++){

		if(($nowPage - $now_cool_page) <= 0 ){
			$page = $i;
		}elseif(($nowPage + $now_cool_page - 1) >= $totalPages){
			$page = $totalPages - $rollPage + $i;
		}else{
			$page = $nowPage - $now_cool_page_ceil + $i;
		}
		if($page > 0 && $page != $nowPage){

			if($page <= $totalPages){
				$link_page .= '<a class="num" href="' . $url.$page.$config['html_suffix'] . '">' . $page . '</a>';
			}else{
				break;
			}
				
		}else{
			if($page > 0 && $totalPages != 1){
				$link_page .= '<span class="current">' . $page . '</span>';
			}
		}

	}


	//替换分页内容
	$page_str = str_replace(
			array('%header%', '%nowPage%', '%upPage%', '%downPage%', '%first%', '%linkPage%', '%end%', '%totalRow%', '%totalPage%'),
			array($header, $nowPage, $up_page, $down_page, $the_first, $link_page, $the_end, $totalRows, $totalPages),
			$theme);
	return "<div class=\"pagination\">{$page_str}</div>";
}

/**
 * 获取数据跟分页，通用方法
 * @param unknown $path 跟路径
 * @param unknown $get $_GET
 * @param unknown $map 额外的类型
 * @param unknown $m 数据模型
 * @param unknown $pagesize 一页的记录数，默认为10
 * @return string
 */
function _get_list_data($path,$get,$map,$m,$pagesize,$order){
	if(!$pagesize) $pagesize = 10; //默认为10
	$get['p']?$cur = $get['p']:$cur = 1;
		
	$mapp = $get;
	unset($mapp['_URL_']);
	unset($mapp["__hash__"]);
	$time1 = 0;
	$time2 = date('Y-m-d H:i:s');
	foreach($mapp as $k=>$v){
		if($v){
			if($k != 'start_time' && $k != 'end_time' && $k != 'p' && $k != 'searchtype' && $k != 'keywords'){
				$map[$k] = $v;
			}
			else{
				if($k == 'start_time') $time1 = $v;
				if($k == 'end_time') $time2 = $v;
			}
			if($k != 'p'){
				$path .= $k.'/'.$v.'/';
			}	
			
		}
	}
	if($_GET['searchtype'] && $_GET['keywords']){
		$map[$_GET['searchtype']] = array('like','%'.$_GET['keywords'].'%');
	}
	$map['update_time'] = array('between',array($time1,$time2));
	$data = _uiclist($m,$map,$cur,$pagesize,$order,1);
	if($cur > 1 && count($data) == 0){
		redirect($path.'p/'.($cur-1)); //当前页每页数据、切当前页非第一页，则调到上一页
	}
	
 	//echo $m->_sql(); //打印sql
	$pagetpl = _to_page($data['count'],$cur,$pagesize,$path.'p/');
	
	$result['data'] = $data;
	$result['pagetpl'] = $pagetpl;
	return $result;
}

function _createFolder($path){
	//第一个条件，不能在根目录创建文件夹
	$t = explode('/', $path);
	if(count($t) != 2){
		if (!file_exists($path))
		{
			_createFolder(dirname($path));
			mkdir($path, 0777);
		}
	}
}

/**
 * 删除文件夹及其文件夹下所有文件
 * @param unknown $dir
 * @param unknown $self 是否删除自身
 * @return boolean
 */
function deldir($dir,$self) {
	//先删除目录下的文件：
	$dh=opendir($dir);
	while ($file=readdir($dh)) {
		if($file!="." && $file!="..") {
			$fullpath=$dir."/".$file;
			if(!is_dir($fullpath)) {
				unlink($fullpath);
			} else {
				deldir($fullpath);
			}
		}
	}

	closedir($dh);
	if($self){
		//删除当前文件夹：
		if(rmdir($dir)) {
			return true;
		} else {
			return false;
		}
	}else{
		return true;
	}

}

/*
 * 中文截取，支持gb2312,gbk,utf-8,big5
* @param string $str 要截取的字串
* @param int $start 截取起始位置
* @param int $length 截取长度
* @param string $charset utf-8|gb2312|gbk|big5 编码
* @param $suffix 是否加尾缀
*/

function csubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
	if(function_exists("mb_substr"))
	{
		if(mb_strlen($str, $charset) <= $length) return $str;
		$slice = mb_substr($str, $start, $length, $charset);
	}
	else
	{
		$re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
		$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
		$re['gbk']          = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
		$re['big5']          = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
		preg_match_all($re[$charset], $str, $match);
		if(count($match[0]) <= $length) return $str;
		$slice = join("",array_slice($match[0], $start, $length));
	}
	if($suffix) return $slice."…";
	return $slice;
}

/**
 * 将中文编码
 * @param array $data
 * @returnstring
 */
function ch_urlencode($data) {
	if (is_array($data) || is_object($data)) {
		foreach ($data as $k => $v) {
			if (is_scalar($v)) {
				if (is_array($data)) {
					$data[$k] = urlencode($v);
				} elseif (is_object($data)) {
					$data->$k = urlencode($v);
				}
			} elseif (is_array($data)) {
				$data[$k] = ch_urlencode($v); //递归调用该函数

			} elseif (is_object($data)) {
				$data->$k = ch_urlencode($v);
			}
		}
	}
	return $data;
}
/*
 * 解决json中文编码问题的方法
 */
function ch_json_encode($data) {
	$ret = ch_urlencode($data);
	$ret = json_encode($ret);
	return urldecode($ret);
}

/*
 * 获取随机字符串
 */
function get_rand_char($length){
	$str = null;
	$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
	$max = strlen($strPol)-1;

	for($i=0;$i<$length;$i++){
		$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
	}
	return $str;
}

/*
 * 获取随机字符串
 */
function get_rand_num($length){
	$str = null;
	$strPol = "0123456789";
	$max = strlen($strPol)-1;

	for($i=0;$i<$length;$i++){
		$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
	}
	return $str;
}

/**
* HuHaiqin的可逆加密
*/
function encrypt($data,$key){

	$key = md5($key);
	$data = base64_encode($data);
	$len = strlen($data);
	//$dataArr = mb_str_split($data); 
	//$len = count($dataArr);
	$keyLen = strlen($key);
	$str = "";
	for($i = 0 ;$i < $len ; $i++){
		if($keyLen > $i){
			//$str .= $dataArr[$i].$key{$i};
			$str .= $data{$i}.$key{$i};
		}else{
			$str .= $data{$i};
			//$str .= $dataArr[$i];
		}
	}
	echo $str."<br>";
	return base64_encode($str);
}



/**
* HuHaiqin 可逆算法
*/
function decrypt($data,$key){
	$str = "";	
	$key = md5($key);
	$keyLen = strlen($key);
	
	$result = mb_str_split(base64_decode($data));
	//$retLen = mb_strlen($result,"UTF-8");
	
	$retLen = count($result);
	$len = 0;
	if($retLen / 2 >= $keyLen ){
		$len = $retLen - $keyLen;
	}else{
		$len = $retLen / 2;
	}

	for($i = 0 ;$i < $len ; $i++){
		if($keyLen > $i){
			//$str .= $result[$i*2];
			$str .= $result{$i*2};
		}else{
			$str .= $result{$i};
			//$str .= $result[$i];
		}
	}
	return base64_decode($str);
}

/**
* 中文字符串分割
*/
function mb_str_split($str,$split_length=1,$charset="UTF-8"){
	if(func_num_args()==1){
	  return preg_split('/(?<!^)(?!$)/u', $str);
	}
	if($split_length<1)return false;
	$len = mb_strlen($str, $charset);
	$arr = array();
	for($i=0;$i<$len;$i+=$split_length){
	  $s = mb_substr($str, $i, $split_length, $charset);
	  $arr[] = $s;
	}
	return $arr;
}
/*
加密解密算法，可逆，弃用，HuHaiqin设计了一套新的算法
function encrypt($data, $key){
	$key = md5($key);
	$x  = 0;
	$len = strlen($data);
	$l  = strlen($key);
	for ($i = 0; $i < $len; $i++)
	{
		if ($x == $l){
			$x = 0;
		}
		$char .= $key{$x};
		$x++;
	}
	for ($i = 0; $i < $len; $i++){
		$str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
	}
	return base64_encode($str);
}

 
function decrypt($data, $key)
{
	$key = md5($key);
	$x = 0;
	$data = base64_decode($data);
	$len = strlen($data);
	$l = strlen($key);
	for ($i = 0; $i < $len; $i++)
	{
		if ($x == $l){
			$x = 0;
		}
		$char .= substr($key, $x, 1);
		$x++;
	}
	for ($i = 0; $i < $len; $i++){
		if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))){
			$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
		}
		else{
			$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
		}
	}
	return $str;
}
*/

//判断微信浏览器打开
function is_weixin()
{
	if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
		return true;
	}
	return false;
}

function error404(){
	header('HTTP/1.1 404 Not Found');
	header("status: 404 Not Found");
}

/**
 * 关键词描红
 * @param unknown $key
 * @param unknown $str
 * @return mixed
 */
function replace_query_str($key,$str){
	return str_replace($key,'<span style="color:red">'.$key.'</span>',$str);
}

/**
 * 处理插件钩子
 * @param string $hook   钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
function hook($hook,$params=array()){
	\Think\Hook::listen($hook,$params);
}
/**
 * 获取插件类的类名
 * @param strng $name 插件名
 */
function get_addon_class($name){
	$class = "Addons\\{$name}\\{$name}Addon";
	return $class;
}

/**
 * 获取插件类的配置文件数组
 * @param string $name 插件名
 */
function get_addon_config($name){
	$class = get_addon_class($name);
	if(class_exists($class)) {
		$addon = new $class();
		return $addon->getConfig();
	}else {
		return array();
	}
}

/**
 * 插件显示内容里生成访问插件的url
 * @param string $url url
 * @param array $param 参数
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function addons_url($url, $param = array()){
	$url        = parse_url($url);
	$case       = C('URL_CASE_INSENSITIVE');
	$addons     = $case ? parse_name($url['scheme']) : $url['scheme'];
	$controller = $case ? parse_name($url['host']) : $url['host'];
	$action     = trim($case ? strtolower($url['path']) : $url['path'], '/');

	/* 解析URL带的参数 */
	if(isset($url['query'])){
		parse_str($url['query'], $query);
		$param = array_merge($query, $param);
	}

	/* 基础参数 */
	$params = array(
			'_addons'     => $addons,
			'_controller' => $controller,
			'_action'     => $action,
	);
	$params = array_merge($params, $param); //添加额外参数

	return U('Addons/execute', $params);
}

//基于数组创建目录和文件
function create_dir_or_files($files){
	foreach ($files as $key => $value) {
		if(substr($value, -1) == '/'){
			mkdir($value);
		}else{
			@file_put_contents($value, '');
		}
	}
}
/**
 * 对查询结果集进行排序
 * @access public
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param array $sortby 排序类型
 * asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list,$field, $sortby='asc') {
	if(is_array($list)){
		$refer = $resultSet = array();
		foreach ($list as $i => $data)
			$refer[$i] = &$data[$field];
		switch ($sortby) {
			case 'asc': // 正向排序
				asort($refer);
				break;
			case 'desc':// 逆向排序
				arsort($refer);
				break;
			case 'nat': // 自然排序
				natcasesort($refer);
				break;
		}
		foreach ( $refer as $key=> $val)
			$resultSet[] = &$list[$key];
		return $resultSet;
	}
	return false;
}
/**
 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
 * @param  string $str  要分割的字符串
 * @param  string $glue 分割符
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function str2arr($str, $glue = ','){
	return explode($glue, $str);
}

/**
 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
 * @param  array  $arr  要连接的数组
 * @param  string $glue 分割符
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function arr2str($arr, $glue = ','){
	return implode($glue, $arr);
}

/**
 * 获取系统中的分组
 * @param array $filter 过滤的分组名
 * @return array 分组数组
 */
function get_dir_file_list($path,$filter){
	//$path = substr(APP_PATH,0,strlen(APP_PATH)-1);
	$data = array();
	if(is_dir($path)){
		$dp=dir($path);
		while($file=$dp->read()){
				
			if($file!='.'&& $file!='..'){
				if($file){
					if(!in_array($file,$filter)){
						$data[] = $file;
					}
				}
			}
				
		}
		$dp->close();
	}
	return $data;
}

/**
 * 获取文件夹下的所有文件路径
 * @param string $dir
 * @return multitype:
 */
function getDir($dir){
	$data=array();
	searchDir($dir,$data);
	return   $data;
}
function searchDir($path,&$data){
	if(is_dir($path)){
		$dp=dir($path);
		while($file=$dp->read()){
			if($file!='.'&& $file!='..'){
				searchDir($path.'/'.$file,$data);
			}
		}
		$dp->close();
	}
	if(is_file($path)){
		$data[]=$path;
	}
}
/*
 * 获取分页列表数据
 */
function _uiclists($model,$get,$map,$cur,$size,$order,$isrelation){
	if(!$size) $size = C('PAGE_SIZE');

	if(!$order){
		$pk = $model->getPk();
		$order = "$pk desc";
	}
	$isrelation ? $isrelation = true : $isrelation = false;
	if($isrelation){
		if($get['role']=='student'){
			$sql = "SELECT DISTINCT A.*,B.`sname`,B.`name` FROM mini_users A JOIN mini_classrooms B JOIN mini_users_student_classroom_relation C WHERE A.`role` = 'student' AND A.`uid` = C.`uid` AND C.`cid` = B.`id` ORDER BY A.`uid` DESC";
			$sql .= ' limit '.($cur-1)*$size.','.$size;
			$Model = new Model();
			$data['list'] = $Model->query($sql);
		}else{
			$data['list'] = $model->where($map)->order($order)->page($cur.','.$size)->relation($isrelation)->select();
		}
	}else{

		$data['list'] = $model->where($map)->order($order)->page($cur.','.$size)->select();
	}
	$data['count'] = $model->where($map)->count();
	return $data;

}

//获取学校角色权限树
 function school_get_auth_tree($role){
		if(in_array($role,C('SCHOOL_ADMIN_ROLE'))){
			$map['title']=$role;
			$map['status'] = 1;
			$temparr=M('SchoolAuthGroup')->where($map)->find();
			$maps['id']=array(in,$temparr['rules']);
		}
          $maps['status']=1;
		$data =M('SchoolAuthRule')->where($maps)->order('listorder desc')->select();
		$tree = new \Think\Tree();
		$tree->init($data);
		$treedata = $tree->get_tree_array(0, $str);
		return $treedata;
    }


/**
 * 获取数据跟分页，通用方法
 * @param unknown $path 跟路径
 * @param unknown $get $_GET
 * @param unknown $map 额外的类型
 * @param unknown $m 数据模型
 * @param unknown $pagesize 一页的记录数，默认为10
 * @return string
 */
function _get_list_datas($path,$get,$map,$m,$pagesize,$order){

	if(!$pagesize) $pagesize = 10; //默认为10
	$get['p']?$cur = $get['p']:$cur = 1;
		
	$mapp = $get;
	unset($mapp['_URL_']);
	unset($mapp["__hash__"]);
	$time1 = 0;
	$time2 = date('Y-m-d H:i:s');
	foreach($mapp as $k=>$v){
		if($v){
			if($k != 'start_time' && $k != 'end_time' && $k != 'p' && $k != 'searchtype' && $k != 'keywords'){
				$map[$k] = $v;
			}
			else{
				if($k == 'start_time') $time1 = $v;
				if($k == 'end_time') $time2 = $v;
			}
			if($k != 'p'){
				$path .= $k.'/'.$v.'/';
			}	
			
		}
	}
	if($_GET['searchtype'] && $_GET['keywords']){
		$map[$_GET['searchtype']] = array('like','%'.$_GET['keywords'].'%');
	}
	$map['update_time'] = array('between',array($time1,$time2));

	$data = _uiclists($m,$get,$map,$cur,$pagesize,$order,1);
	if($cur > 1 && count($data) == 0){
		redirect($path.'p/'.($cur-1)); //当前页每页数据、切当前页非第一页，则调到上一页
	}
	
 	//echo $m->_sql(); //打印sql
	$pagetpl = _to_page($data['count'],$cur,$pagesize,$path.'p/');
	
	$result['data'] = $data;
	$result['pagetpl'] = $pagetpl;
	return $result;
}

/**
 * token生成、检测、删除类
 * @author HuHaiqin
 *
 */
class Token{
	const SESSION_KEY = 'SESSION_KEY';
	/**
	 * 生成一个当前的token
	 * @param string $form_name
	 * @return string
	 */
	public static function grante_token($form_name)
	{
		$key = self::grante_key();
		$_SESSION['SESSION_KEY.$form_name'] = $key;
		$token = md5(substr(time(), 0, 3).$key.$form_name);
		return $token;
	}

	/**
	 * 验证一个当前的token
	 * @param string $form_name
	 * @return string
	 */
	public static function is_token($form_name,$token)
	{
		$key = $_SESSION['SESSION_KEY.$form_name'];
		$old_token = md5(substr(time(), 0, 3).$key.$form_name);
		if($old_token == $token)
		{
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 删除一个token
	 * @param string $form_name
	 * @return boolean
	 */
	public static function drop_token($form_name)
	{
		unset($_SESSION['SESSION_KEY.$form_name']);	
		return true;
	}

	/**
	 * 生成一个密钥
	 * @return string
	 */
	public static function grante_key()
	{
		$encrypt_key = md5(((float) date("YmdHis") + rand(100,999)).rand(1000,9999));
		return $encrypt_key;
	}
}